<template>
  <div class="flex" style="align-items: flex-end;">
    <div class="file flex flex-center">
      <div v-permissionShow v-if="fileName == ''" class="flex flex-center pointer" @click="chooseFile">
        <img src="@/assets/icon/upload.png" style="width: 20px;height: 20px; margin-right: 10px">
        <span>{{ $t('pageStr.chooseFileStr') }}</span>
      </div>
      <div v-else class="flex flex-center">
        <div>
          {{ fileName }}
        </div>
        <el-icon color="#E06363" :size="20" class="pointer"
                 @click="delFile">
          <CloseBold/>
        </el-icon>
      </div>
    </div>
    <input ref="inputRef" id="open" style="display: none" name="fileName" :accept="accept" type="file"
           @change="changeFile">
    <el-button class="ml-10 default-btn" @click="handleUpload" :loading="isLoading">
      {{ btnLabel }}
    </el-button>
  </div>
</template>

<script setup>
import {ref, defineProps, defineEmits, onMounted} from 'vue'
import {reqStopApp} from "@/api/data-collect/edps-upgrade";
import {reqUploadFile} from "@/api/file/file-upload";
import {ElMessage} from "element-plus";
import {useI18n} from 'vue-i18n'
import config from '~/config'

const isLoading = ref(false)
const {t} = useI18n()
const inputRef = ref(null)

const props = defineProps({
  // 上传路径
  url: {
    type: String,
    default: ''
  },
  // 上传按钮的文字
  btnLabel: {
    type: String,
    default: ''
  },
  // 过滤的文件类型
  accept: {
    type: String,
    default: ''
  },
  // 过滤的文件表单内名称
  fileName: {
    type: String,
    default: 'file'
  },
  // 是否需要stopApp
  isStop: {
    type: Boolean,
    default: false
  },
  // 是否需要分片
  isResumable: {
    type: Boolean,
    default: false
  },
  isChecked: {
    type: Boolean,
    default: false
  }
})
// 上传成功返回的事件
const emits = defineEmits(['uploadSuccess'])
const fileName = ref('')
var r = null
onMounted(() => {
  if (props.isResumable) {
    r = new Resumable({
      target: config[import.meta.env.MODE].baseUrl + '/system/uploadImage',
      chunkSize: 0.5 * 1024 * 1024,
      simultaneousUploads: 1,
      testChunks: false,
      throttleProgressCallbacks: 1,
      fileType: [".ky"],
      clearInput: false,
      fileTypeErrorCallback: function (file, errorCount) {
        // showReturnMsg([g_alertStr.errFileFormat]);
        inputRef.value.value = ''
        for (let index = 0; index < r.files.length; index++) {
          var file = r.files[index];
          r.removeFile(file);
        }

      },
      minFileSizeErrorCallback: function (file, errorCount) {
        // showReturnMsg([g_alertStr.errFileEmpty]);
        inputRef.value.value = ''
        for (let index = 0; index < r.files.length; index++) {
          var file = r.files[index];
          r.removeFile(file);
        }
      }
    });
    r.assignBrowse(inputRef.value);
    if (!r.support) {
      console.log('nosuppoert')
      alert("Browser not support");
    } else {
      // Handle file add event
      r.on('fileAdded', function (file) {
        console.log("fileAdded");
      });

      r.on('fileSuccess', function (file, message) {
        // Reflect that the file upload has completed
        console.log("fileSuccess");
        isLoading.value = false
        const formData = new FormData();
        formData.append("keepSet", props.isChecked ? "on" : "off");
        // reqUploadFile('/system/upgradeFirmware', formData)
      });
      r.on("fileError", function (file, message) {
        // Reflect that the file upload has resulted in error
        console.log("fileError");
        isLoading.value = false
      });
      r.on("fileProgress", function (file) {
        // Handle progress for both the file and the overall upload
        console.log("fileProgress:" + file.progress() * 100 + "%");
      });
      r.on("uploadStart", function () {
        console.log("uploadStart");
      });
    }
  }
})

/**
 * 上传文件
 */
async function handleUpload() {
  const file = inputRef.value.files[0]
  console.log('上传文件', file)
  // 如果文件不存在直接报错返回
  if (!file) {
    ElMessage.error(t('pageStr.noFileStr'))
    return
  }
  isLoading.value = true
  // 分片上传的操作逻辑
  if (props.isResumable) {
    await reqStopApp()
    r.upload();
    return
  }
  if (props.url == '') {
    ElMessage.error('没设置上传组件url！')
    isLoading.value = false
    return
  }

  const formData = new FormData()
  formData.append(props.fileName, file);
  try {
    // 如果需要停止
    if (props.isStop) {
      await reqStopApp()
    }
    const res = await reqUploadFile(props.url, formData)
    emits("uploadSuccess", res.data)
  } catch (e) {
    ElMessage.error(t('errorTip'))
  } finally {
    isLoading.value = false
  }

}

/**
 * 删除文件
 */
function delFile() {
  // 响应式的文件名
  fileName.value = ''
  // 清空input的value
  inputRef.value.value = ''
}

/**
 * 文件变化
 */
function changeFile() {
  if (inputRef.value == null) {
    return
  }
  // 获取响应式文件名
  fileName.value = inputRef.value.files[0].name
  console.log('选择文件', fileName.value)
}

/**
 * 点击选择文件
 */
function chooseFile() {
  // 模拟input被点击
  inputRef.value.click()
}


</script>

<style lang="scss" scoped>
.file {
  width: 480px;
  height: 80px;
  background-color: #F5F6FA;
  border: #A0A2B9 1px dashed;
  border-radius: 4px;
}
</style>
